<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/16
 * Time: 21:00
 */
namespace Pay\Controller;

use Common\Common\Api\Redis\Channel;

/**
 * Class ManyiController
 * @package Pay\Controller
 * 2019/7/8 ajie 汇通3
 */
class Huifutong3Controller extends PayController{
    protected $config;
    protected $class;
    public function __construct(){
        parent::__construct();
        $classes = explode("\\",__CLASS__);
        $class = end($classes);
        $this->class = substr($class, 0, stripos($class, "Controller"));
    }

    public function pay($array){
        $this->config = Channel::getInstance()->getById($array['channel']);

        if(!$this->config){
            $this->showmessage('通道错误!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $parameter = array(
            'code' => $this->config['code'], // 通道名称
            'title' => $this->config['title'],
            'exchange' => 1, // 金额比例
            'gateway' => $this->config['gateway'],
            'orderid' => createOrderId(),
            'out_trade_id' => I("request.pay_orderid"),
            'body' => 'pay',
            'channel'=>$array
        );

        $return = $this->orderadd( $parameter );

        switch($this->config['paytype']){
            case 1:
            case 2:
                $pay_bankcode = '1';
                break;
            //支付宝
            case 17:
            case 18:
                $pay_bankcode = '3';//支付宝转账
                break;
            default:
                $this->showmessage('暂不支持此方式!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $isMobile = isMobile();
        $terminal  = 1;
        if($isMobile){
            $terminal  = 0;
        }

        $data = array(
            "mch_id" => $this->config['mch_id'], //商户号
            "out_trade_no" => $return['orderid'], //商户订单号
            "total_fee" => strval($return['amount']*100), //支付金额 单位分
            "attach" => '', //附加信息
            "notify_url" => $return['notifyurl'], //异步回调 , 支付结果以异步为准
            "callback_url" => $return['callbackurl'], //同步回调 不作为最终支付结果为准，请以异步回调为准
            "trade_type" => $pay_bankcode, //支付类型 此处可选项以网站对接文档为准 等参考API
            "terminal" => $terminal, //请求终端 【0：手机&平板；1：PC电脑】
            "ip" => getIP(), //支付端ip地址
            'pwdcode' =>'', //支付宝口令红包码
        );
        $data["sign"] = md5($data["mch_id"] . $data["out_trade_no"] . $data["total_fee"] . $data["notify_url"] . $this->config['signkey']); //加密


        $res = curl($this->config['gateway'], httpstr($data));
        $resp = json_decode($res, true);

        /**
        array(2) {
        ["status"]=>
        int(1)
        ["data"]=>
        array(4) {
        ["name"]=>
        string(6) "张飞"
        ["price"]=>
        string(6) "100.00"
        ["qrcode"]=>
        string(46) "https://img.1230168.com/paycode/1562639366.png"
        ["payurl"]=>
        string(64) "https://www.wiwkce.cn/api/index/toaccount/sn20190709104926954.do"
        }
        }
         */

       // var_dump('<pre/>',$this->config['gateway'],$data,$res,$resp);exit();

        $code = $resp['data']['qrcode'];

        if(!$code){
            if($resp['error']){
                $this->showmessage($resp['error'],['code'=>C("THIRDCODES.".$this->class)]);
            }
            $this->showmessage("获取支付链接失败",['code'=>C("THIRDCODES.".$this->class)]);
        }

            $paytype = transArr( C("PAYTYPES"), "id");
            $this->assign("wap_url", $code);
             $this->assign("code_url", $code);
            $this->assign("title", $paytype[$this->config['paytype']]);
            $this->assign("return", $return);
            //$this->assign("imgurl", C("website.DOMAIN")."/Pay_Qrcode_getCode?type=1&data=" . base64_encode($code));
            switch($this->config['paytype']){
                //微信
                case 1:
                    if($isMobile){
                        $this->display("WeiXin/weixinwap");
                    }else{
                        $this->display("WeiXin/weixin");
                    }
                    break;
                //支付宝扫码
                case 3:
                    //支付宝H5
                case 4:
                case 17:
                case 18:
                    if(isMobile()){
                        header("location: {$resp['data']['payurl']}"); exit;
                    }else{
                        $this->display("WeiXin/alipay");
                    }
                    break;
                default:
                    $this->display("WeiXin/Pay");
            }

    }

    //通知
    public function notifyurl(){
        //$this->debug_callback();
        if(!$this->checkip(getIP(),['43.249.195.142'])){
            exit("wrong");
        }
        $p = json_decode(file_get_contents("php://input"), true);

        /**
        array(9) {
        ["mch_id"]=>
        int(10198)
        ["out_trade_no"]=>
        string(19) "sn20190709105759709"
        ["transaction_id"]=>
        string(19) "2019070910571480276"
        ["total_fee"]=>
        int(1000)
        ["attch"]=>
        string(0) ""
        ["trade_type"]=>
        string(1) "3"
        ["endtime"]=>
        int(1562641111)
        ["result_code"]=>
        string(7) "SUCCESS"
        ["sign"]=>
        string(32) "5e66f796718ae2e1b648b47f3ff17993"
        }
         */

        if(empty($p)){
            exit("");
        }



        //获取订单信息
        $orderid = $p['out_trade_no'];
        $find = $this->checkOrderNotify($orderid);
        if(!$find){
            echo 'order_not_found'; exit;
        }

        //保存回调数据
        M("Order")->where(array("pay_orderid"=>$orderid))->save(array(
            "pay_orderid_rd"=> htmlspecialchars($p['transaction_id'])
        ));

        $this->config = Channel::getInstance()->find(['code'=>$this->class]);

        if($p['result_code'] !== 'SUCCESS'){
            exit("fail");
        }

        $sign = $p['sign'];

        //签名【md5(订单状态+商务号+商户订单号+平台订单号+支付金额+商户秘钥)】
        $sign2 = md5($p['result_code'] . $p['mch_id'] . $p['out_trade_no'] . $p['transaction_id']. $p['total_fee'] . $this->config['signkey']);

        if($sign !== $sign2){
            echo 'sign_wrong';exit;
        }

        $this->async($find['pay_orderid'],'success');
    }

    public function callBackUrl(){

        echo '操作成功'; exit;
    }
}